package com.cory.admin.sys.service;

import java.util.List;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beust.jcommander.internal.Lists;
import com.cory.admin.sys.domain.entity.SysUserRole;
import com.cory.admin.sys.mapper.SysUserRoleMapper;

/**
 *  服务实现类
 *
 * @author xc
 * @since 2019-02-23
 */
@Service
public class SysUserRoleService extends ServiceImpl<SysUserRoleMapper, SysUserRole> {

    public List<Integer> selectUserRoleIds(Integer userId) {
        return baseMapper.selectUserRoleIds(userId);
    }
    
    public boolean hasUserRole(Integer userId, Integer roleId) {
        if (userId == null || roleId == null) {
            return false;
        }
        
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("role_id", roleId);
        if (super.getOne(wrapper) != null) {
            return true;
        }
        
        return false;
    }
    
    @Transactional(rollbackFor=Exception.class)
    public void saveUserRoles(Integer userId, List<Integer> roleIds) {
        List<Integer> userRoleIds = this.selectUserRoleIds(userId);
        
        List<Integer> addRoleIds = roleIds.stream().filter(i -> !userRoleIds.contains(i)).collect(Collectors.toList());
        List<Integer> delRoleIds = userRoleIds.stream().filter(i -> !roleIds.contains(i)).collect(Collectors.toList());
        
        List<SysUserRole> addRoles = Lists.newArrayList();
        for (Integer roleId : addRoleIds) {
            SysUserRole role = new SysUserRole();
            role.setUserId(userId);
            role.setRoleId(roleId);
            
            addRoles.add(role);
        }
        if (addRoles.size() > 0) {
            super.saveBatch(addRoles);
        }
        
        if (delRoleIds.size() > 0) {
            UpdateWrapper<SysUserRole> wrapper = new UpdateWrapper<>();
            wrapper.eq("user_id", userId).in("role_id", delRoleIds);
            super.remove(wrapper);
        }
        
    }

}
